#!/usr/bin/env bash

# $1 - directory with git
if [ -z "$1" ]; then
	exit 1
fi

set -efu
trap popd exit

LOG="${LOG:-/tmp/merge-to-rosa201905.log}"

pushd "$1"

git fetch --all
git reset origin/rosa2019.1 --hard
if ! git checkout rosa2019.05 ; then
	echo "FAIL;${1};no-branch-rosa2019.05" | tee -a "$LOG"
	exit 1
fi
	
h="$(git show HEAD)"
RESET=0
if echo "$h" | grep -E '^Author:.*alexander@mezon.ru.*' && echo "$h" | grep -E 'MassBuild.*Increase release tag'
	then RESET=1
fi

# https://github.com/mikhailnov/rpm-info-web-api
#readonly API_URL="http://abf-downloads.rosalinux.ru:8050:/rpm-info-web-api.cgi"
#ver_201910="$(wget -qO- ${API_URL}?package=${1}&platform=rosa2019.1&arch=x86_64&repo=main/release&query_fields=VERSION)"
#ver_201900="$(wget -qO- ${API_URL}?package=${1}&platform=rosa2019.0&arch=x86_64&repo=main/release&query_fields=VERSION)"
ver_201910="$(ssh mikhailnov@abf-downloads.rosalinux.ru /home/mikhailnov/ssh-api.sh "$1" rosa2019.1)"
ver_201900="$(ssh mikhailnov@abf-downloads.rosalinux.ru /home/mikhailnov/ssh-api.sh "$1" rosa2019.0)"
MERGE=0
if [ -z "$ver_201910" ] || [ -z "$ver_201900" ]; then
	echo "SKIPPED;${1};empty-version" | tee -a "$LOG"
	exit 1
fi
# rpmdev-vercmp is a python3 script, depends from python3-rpm only
case "$(rpmdev-vercmp "$ver_201910" "$ver_201900" | head -n 1 | awk '{print $2}')" in
	"<" ) MERGE=0 ;;
	">" ) MERGE=0 ;;
	"==" ) MERGE=1 ;;
	* ) echo "Unexpected answer from vercmp!" ; exit 1 ;;
esac

if [ "$RESET" = 1 ] && [ "$MERGE" = 1 ] ; then	
	reset_target="$(git log | grep '^commit ' | head -n 2 | tail -n 1 | awk '{print $NF}')"
	git reset --hard "$reset_target"
fi

if [ "$MERGE" = 1 ]; then
	if git diff rosa2019.05..rosa2019.1 | grep '^\+' | grep -qE '%package.*python2' ; then
		echo "SKIPPED;${1};py2-naming" | tee -a "$LOG"
		exit
	fi
	# git may have been not built
	if git diff rosa2019.05..rosa2019.1 | grep -qi '^\+Version:' ; then
		echo "SKIPPED;${1};versions-differ-in-git-but-pkgs-are-same" | tee -a "$LOG"
		exit
	fi
	git pull --no-edit origin rosa2019.1
	git push origin +rosa2019.05
else
	echo "SKIPPED;${1};no-merge" | tee -a "$LOG"
fi
